package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 作用: 添加购物车
     *
     * @param shoppingCart 当前提交的购物项的数据
     * @return
     */
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        //1. 根据用户的id与dish_id 或者setmeal_id查看购物车表是否存在该购物项
        ShoppingCart shoppingCartOne = shoppingCartMapper.findUserIdAndDishIdOrSetmealId(shoppingCart);
        //2.如果查询是空,则插入一条记录
        if (shoppingCartOne == null) {
            //补全数据
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.save(shoppingCart);
            shoppingCartOne = shoppingCart;
        } else {
            //3.不为空的话,数量+1
            shoppingCartOne.setNumber(shoppingCartOne.getNumber() + 1);
            shoppingCartMapper.update(shoppingCartOne);
        }
        return shoppingCartOne;
    }

    /**
     * 作用: 查看购物车
     *
     * @param userId 用户Id
     */
    @Override
    public List<ShoppingCart> findShoppingCartByUserId(Long userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findShoppingCartByUserId(userId);
        return shoppingCartList;
    }

    /**
     * 作用: 清空购物车
     *
     * @param userId@return
     */
    @Override
    public void clean(Long userId) {
        shoppingCartMapper.clean(userId);
    }

    /**
     * 删除当前购物车上的商品
     *
     * @return
     */
    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart) {
        //1. 根据用户的id与dish_id 或者setmeal_id查看购物车表是否存在该购物项
        ShoppingCart shoppingCartOne = shoppingCartMapper.findUserIdAndDishIdOrSetmealId(shoppingCart);
        if (shoppingCartOne.getNumber()>1) {
            shoppingCartOne.setNumber(shoppingCartOne.getNumber() - 1);
            shoppingCartMapper.sub(shoppingCartOne);
        }else {
               shoppingCartMapper.deletdish(shoppingCart);
        }
        return shoppingCartOne;
    }
}
